// AI侦探应用数据访问层实现

// 数据模型导入
import { Case, Suspect, Victim, Investigator, Clue, AIAnalysis } from './MODEL_DEFINITIONS';

// ========== 数据访问接口定义 ==========

// 通用数据源接口
export interface DataSource<T> {
  getAll(): Promise<Array<T>>;
  getById(id: string): Promise<T | null>;
  save(data: T): Promise<boolean>;
  update(id: string, data: T): Promise<boolean>;
  delete(id: string): Promise<boolean>;
}

// 通用仓库接口
export interface Repository<T> {
  getAllItems(): Promise<Array<T>>;
  getItemById(id: string): Promise<T | null>;
  addItem(item: T): Promise<boolean>;
  updateItem(id: string, item: T): Promise<boolean>;
  deleteItem(id: string): Promise<boolean>;
}

// ========== JSON文件存储实现 ==========

// JSON文件数据源基类
abstract class JsonFileDataSource<T> implements DataSource<T> {
  protected abstract getFileName(): string;
  protected abstract deserialize(jsonStr: string): Array<T>;
  protected abstract serialize(data: Array<T>): string;

  async getAll(): Promise<Array<T>> {
    try {
      // #ifdef PREVIEW
      // 在预览模式下，这里会返回空数组，由Mock数据源提供数据
      return [];
      // #else
      // 真实环境下读取JSON文件
      /*
      const fileContent = await this.readFile(this.getFileName());
      return this.deserialize(fileContent);
      */
      // #endif
    } catch (error) {
      console.error(`Failed to get all items from ${this.getFileName()}:`, error);
      return [];
    }
  }

  async getById(id: string): Promise<T | null> {
    try {
      const allItems = await this.getAll();
      return allItems.find(item => (item as any).id === id) || null;
    } catch (error) {
      console.error(`Failed to get item by id from ${this.getFileName()}:`, error);
      return null;
    }
  }

  async save(data: T): Promise<boolean> {
    try {
      const allItems = await this.getAll();
      allItems.push(data);
      // #ifdef PREVIEW
      return true; // 预览模式下模拟成功
      // #else
      /*
      return await this.writeFile(this.getFileName(), this.serialize(allItems));
      */
      // #endif
    } catch (error) {
      console.error(`Failed to save item to ${this.getFileName()}:`, error);
      return false;
    }
  }

  async update(id: string, data: T): Promise<boolean> {
    try {
      const allItems = await this.getAll();
      const index = allItems.findIndex(item => (item as any).id === id);
      if (index === -1) return false;
      
      // 更新时间戳
      if (typeof (data as any).updatedAt === 'object') {
        (data as any).updatedAt = new Date();
      }
      
      allItems[index] = data;
      
      // #ifdef PREVIEW
      return true; // 预览模式下模拟成功
      // #else
      /*
      return await this.writeFile(this.getFileName(), this.serialize(allItems));
      */
      // #endif
    } catch (error) {
      console.error(`Failed to update item in ${this.getFileName()}:`, error);
      return false;
    }
  }

  async delete(id: string): Promise<boolean> {
    try {
      const allItems = await this.getAll();
      const filteredItems = allItems.filter(item => (item as any).id !== id);
      
      // #ifdef PREVIEW
      return true; // 预览模式下模拟成功
      // #else
      /*
      return await this.writeFile(this.getFileName(), this.serialize(filteredItems));
      */
      // #endif
    } catch (error) {
      console.error(`Failed to delete item from ${this.getFileName()}:`, error);
      return false;
    }
  }

  // 读取文件（真实环境下使用）
  private async readFile(fileName: string): Promise<string> {
    // 这里应该使用鸿蒙的文件API读取文件
    // 由于在previewer中无法使用，这里仅提供接口定义
    throw new Error('File operations not available in previewer');
  }

  // 写入文件（真实环境下使用）
  private async writeFile(fileName: string, content: string): Promise<boolean> {
    // 这里应该使用鸿蒙的文件API写入文件
    // 由于在previewer中无法使用，这里仅提供接口定义
    throw new Error('File operations not available in previewer');
  }
}

// ========== 具体数据源实现 ==========

// 案件数据源
export class CaseDataSource extends JsonFileDataSource<Case> {
  protected getFileName(): string {
    return 'cases.json';
  }

  protected deserialize(jsonStr: string): Array<Case> {
    const data = JSON.parse(jsonStr);
    // 将日期字符串转换为Date对象
    return data.map((item: any) => ({
      ...item,
      occurredTime: new Date(item.occurredTime),
      reportedTime: new Date(item.reportedTime),
      createdAt: new Date(item.createdAt),
      updatedAt: new Date(item.updatedAt)
    }));
  }

  protected serialize(data: Array<Case>): string {
    // 将Date对象转换为字符串
    const serializedData = data.map(item => ({
      ...item,
      occurredTime: item.occurredTime.toISOString(),
      reportedTime: item.reportedTime.toISOString(),
      createdAt: item.createdAt.toISOString(),
      updatedAt: item.updatedAt.toISOString()
    }));
    return JSON.stringify(serializedData);
  }
}

// 嫌疑人数据源
export class SuspectDataSource extends JsonFileDataSource<Suspect> {
  protected getFileName(): string {
    return 'suspects.json';
  }

  protected deserialize(jsonStr: string): Array<Suspect> {
    const data = JSON.parse(jsonStr);
    return data.map((item: any) => ({
      ...item,
      createdAt: new Date(item.createdAt),
      updatedAt: new Date(item.updatedAt)
    }));
  }

  protected serialize(data: Array<Suspect>): string {
    const serializedData = data.map(item => ({
      ...item,
      createdAt: item.createdAt.toISOString(),
      updatedAt: item.updatedAt.toISOString()
    }));
    return JSON.stringify(serializedData);
  }
}

// 线索数据源
export class ClueDataSource extends JsonFileDataSource<Clue> {
  protected getFileName(): string {
    return 'clues.json';
  }

  protected deserialize(jsonStr: string): Array<Clue> {
    const data = JSON.parse(jsonStr);
    return data.map((item: any) => ({
      ...item,
      discoveryTime: new Date(item.discoveryTime),
      createdAt: new Date(item.createdAt),
      updatedAt: new Date(item.updatedAt)
    }));
  }

  protected serialize(data: Array<Clue>): string {
    const serializedData = data.map(item => ({
      ...item,
      discoveryTime: item.discoveryTime.toISOString(),
      createdAt: item.createdAt.toISOString(),
      updatedAt: item.updatedAt.toISOString()
    }));
    return JSON.stringify(serializedData);
  }
}

// ========== 仓库实现 ==========

// 通用仓库基类
abstract class BaseRepository<T> implements Repository<T> {
  protected dataSource: DataSource<T>;

  constructor(dataSource: DataSource<T>) {
    this.dataSource = dataSource;
  }

  async getAllItems(): Promise<Array<T>> {
    return await this.dataSource.getAll();
  }

  async getItemById(id: string): Promise<T | null> {
    return await this.dataSource.getById(id);
  }

  async addItem(item: T): Promise<boolean> {
    return await this.dataSource.save(item);
  }

  async updateItem(id: string, item: T): Promise<boolean> {
    return await this.dataSource.update(id, item);
  }

  async deleteItem(id: string): Promise<boolean> {
    return await this.dataSource.delete(id);
  }
}

// 案件仓库
export class CaseRepository extends BaseRepository<Case> {
  constructor(dataSource: DataSource<Case>) {
    super(dataSource);
  }

  // 扩展方法：获取指定状态的案件
  async getCasesByStatus(status: string): Promise<Array<Case>> {
    const allCases = await this.getAllItems();
    return allCases.filter(caseItem => caseItem.status === status);
  }

  // 扩展方法：获取指定调查员的案件
  async getCasesByInvestigator(investigatorId: string): Promise<Array<Case>> {
    const allCases = await this.getAllItems();
    return allCases.filter(caseItem => caseItem.investigatorId === investigatorId);
  }
}

// 嫌疑人仓库
export class SuspectRepository extends BaseRepository<Suspect> {
  constructor(dataSource: DataSource<Suspect>) {
    super(dataSource);
  }

  // 扩展方法：获取指定案件的嫌疑人
  async getSuspectsByCase(caseId: string): Promise<Array<Suspect>> {
    const allSuspects = await this.getAllItems();
    return allSuspects.filter(suspect => suspect.caseId === caseId);
  }

  // 扩展方法：获取指定状态的嫌疑人
  async getSuspectsByStatus(status: string): Promise<Array<Suspect>> {
    const allSuspects = await this.getAllItems();
    return allSuspects.filter(suspect => suspect.status === status);
  }
}

// 线索仓库
export class ClueRepository extends BaseRepository<Clue> {
  constructor(dataSource: DataSource<Clue>) {
    super(dataSource);
  }

  // 扩展方法：获取指定案件的线索
  async getCluesByCase(caseId: string): Promise<Array<Clue>> {
    const allClues = await this.getAllItems();
    return allClues.filter(clue => clue.caseId === caseId);
  }

  // 扩展方法：获取关键线索
  async getKeyClues(): Promise<Array<Clue>> {
    const allClues = await this.getAllItems();
    return allClues.filter(clue => clue.isKeyEvidence);
  }
}

// ========== 数据源工厂 ==========

// 数据源工厂类 - 负责创建适合当前环境的数据源
export class DataSourceFactory {
  // 创建案件数据源
  static createCaseDataSource(): DataSource<Case> {
    // #ifdef PREVIEW
    // 预览模式下返回Mock数据源
    return new MockCaseDataSource();
    // #else
    // 真实环境下返回JSON文件数据源
    return new CaseDataSource();
    // #endif
  }

  // 创建嫌疑人数据源
  static createSuspectDataSource(): DataSource<Suspect> {
    // #ifdef PREVIEW
    return new MockSuspectDataSource();
    // #else
    return new SuspectDataSource();
    // #endif
  }

  // 创建线索数据源
  static createClueDataSource(): DataSource<Clue> {
    // #ifdef PREVIEW
    return new MockClueDataSource();
    // #else
    return new ClueDataSource();
    // #endif
  }
}

// ========== 仓库工厂 ==========

// 仓库工厂类 - 负责创建仓库实例
export class RepositoryFactory {
  // 创建案件仓库
  static createCaseRepository(): CaseRepository {
    return new CaseRepository(DataSourceFactory.createCaseDataSource());
  }

  // 创建嫌疑人仓库
  static createSuspectRepository(): SuspectRepository {
    return new SuspectRepository(DataSourceFactory.createSuspectDataSource());
  }

  // 创建线索仓库
  static createClueRepository(): ClueRepository {
    return new ClueRepository(DataSourceFactory.createClueDataSource());
  }
}

// ========== Mock数据源基类 ==========

// 导入模拟数据
import { mockCases, mockSuspects, mockClues } from './MOCK_DATA';

// Mock数据源基类
abstract class MockDataSource<T> implements DataSource<T> {
  protected abstract getMockData(): Array<T>;

  async getAll(): Promise<Array<T>> {
    return this.getMockData();
  }

  async getById(id: string): Promise<T | null> {
    const allItems = this.getMockData();
    return allItems.find(item => (item as any).id === id) || null;
  }

  async save(data: T): Promise<boolean> {
    console.log('Mock save operation:', data);
    return true;
  }

  async update(id: string, data: T): Promise<boolean> {
    console.log('Mock update operation:', id, data);
    return true;
  }

  async delete(id: string): Promise<boolean> {
    console.log('Mock delete operation:', id);
    return true;
  }
}

// Mock案件数据源实现
class MockCaseDataSource extends MockDataSource<Case> {
  protected getMockData(): Array<Case> {
    return mockCases;
  }
}

// Mock嫌疑人数据源实现
class MockSuspectDataSource extends MockDataSource<Suspect> {
  protected getMockData(): Array<Suspect> {
    return mockSuspects;
  }
}

// Mock线索数据源实现
class MockClueDataSource extends MockDataSource<Clue> {
  protected getMockData(): Array<Clue> {
    return mockClues;
  }
}